<?php
/**
 * Date: 2023/12/15
 * Time: 11:50
 */

namespace App\Logic\Amazon\Api\Parse;

use App\Models\Operation\Business;
use App\Models\Operation\ProfitSku;
use App\Models\Product\ProductAmazonSku;
use App\Models\Product\ProductSku;

class GetSalesAndTrafficReport{

    public static function exe($lines,$accountId,$countryId){

        if(!is_array($lines))return 2;
        $date = $lines['salesAndTrafficByDate'][0]['date'];
        if(!$date)return 2;

        if(!$accountId)return 2;
        if(!$countryId)return 2;
        $i = 0;
        $count = 0;
        try{
            if ($lines['salesAndTrafficByAsin']) {
                foreach($lines['salesAndTrafficByAsin'] as $line){
                    $flag = self::_addBusinessReport($line,$date,$accountId,$countryId);
                    $flag && $count++;
                    $i++;
                    sleep(1);
                }
            }
        }catch (\Exception $e){
            report($e);
        }
        return $i == $count ? 1 : 2;
    }

    /**
     * @param $line
     * @param $date
     * @param $accountId
     * @param $countryId
     * @return bool
     */
    private static function _addBusinessReport($line,$date,$accountId,$countryId){

        //sku信息
        $pskuId = self::_getPSkuID($line['childAsin'],$countryId) ?? 0;
        $classifyId = 0;
        if ($pskuId) {
            $classifyId = ProductSku::getValueById($pskuId, 'classify_id') ?? 0;
        }

        //订单信息
        $ordered = 0;
        $orderedSales = 0;
        if ($line['salesByAsin']) {
            $ordered = $line['salesByAsin']['unitsOrdered'] ?? 0; //订单数量
            if($line['salesByAsin']['orderedProductSales']) {
                $orderedSales = $line['salesByAsin']['orderedProductSales']['amount'] ?? 0; //订单总金额
            }
        }

        //business数据
        $items = [
            'report_date' => $date,
            'acountry_id'  => $accountId ?? 0,
            'country_id'  => $countryId ?? 0,
            'parent_asin' => $line['parentAsin'],
            'child_asin'  => $line['childAsin'],
            'psku_id'     => $pskuId ?? 0,
            'classify_id' => $classifyId ?? 0,

            'sessions_app'       => $line['trafficByAsin']['mobileAppSessions'] ?? 0,
            'sessions_browser'   => $line['trafficByAsin']['browserSessions'] ?? 0,
            'sessions_total'     => $line['trafficByAsin']['sessions'] ?? 0,
            'page_views_app'     => $line['trafficByAsin']['mobileAppPageViews'] ?? 0,
            'page_views_browser' => $line['trafficByAsin']['browserPageViews'] ?? 0,
            'page_views_total'   => $line['trafficByAsin']['pageViews'] ?? 0,
            'ordered'       => $ordered ?? 0,
            'ordered_sales' => $orderedSales ?? 0,
        ];

        $re = Business::query()->create($items);
        return !$re ? false : true;
    }

    private static function _getPSkuID($childAsin,$countryId){
        $pSkuIds = ProductAmazonSku::query()
            ->where('status',1)
            ->where('child_asin',$childAsin)
            ->where('country_id',$countryId)
            ->distinct()
            ->pluck('psku_id');
        $profit = ProfitSku::query()
            ->whereIn('psku_id',$pSkuIds)
            ->where('country_id',$countryId)
            ->where('transport',1)
            ->orderBy('profit_rate','ASC')
            ->first();
        return $profit->psku_id ?? 0;
    }

}
